var express = require("express");
var app = express();
var fs = require('fs');
var path = require('path');

var bodyParser = require('body-parser');

var COMMENTS_FILE = path.join(__dirname, 'comments.json');
app.set('port', (process.env.PORT || 9004));
app.use('/', express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));



//接口api获取评论列表
app.get('/api/comments', function(req, res){
   fs.readFile(COMMENTS_FILE,function(err,data){
   		if(err){
   			console.error(err);
   			process.exit(1);
   		}
   		res.json(JSON.parse(data));
   })
});

//插入数据
app.post('/api/comments', function(req, res) {
  fs.readFile(COMMENTS_FILE, function(err, data) {
    if (err) {
      console.error(err);
      process.exit(1);
    }
    var comments = JSON.parse(data);
  
    var newComment = {
      id: Date.now(),
      author: req.body.author,
      url:req.body.url,
      text: req.body.text,
    };
    comments.push(newComment);
    fs.writeFile(COMMENTS_FILE, JSON.stringify(comments, null, 4), function(err) {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      res.json(comments);
    });
  });
});


app.listen(app.get('port'), function() {
  console.log('Server started: http://localhost:' + app.get('port') + '/');
});
